package com.cn.algorithm.leetcode.array.two;


/*
*
*14. 最长公共前缀
简单
相关标签
相关企业
编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀，返回空字符串 ""。



示例 1：

输入：strs = ["flower","flow","flight"]
输出："fl"
示例 2：

输入：strs = ["dog","racecar","car"]
输出：""
解释：输入不存在公共前缀。


提示：

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
*
* */

public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] res = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix3(res));


    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int length = strs[0].length();
        int count = strs.length;
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }

    public static String longestCommonPrefix2(String[] strs) {
        String res = strs[0];
        String prefix = "";
        String tmp = "";
        for (int i = 0; i < res.length(); i++) {
            prefix += res.charAt(i) + "";
            for (int j = 1; j < strs.length; j++) {
               if (!strs[j].startsWith(prefix)) {
                   return tmp;
               }
            }
            tmp = prefix;
        }
        return tmp;
    }

    public static String longestCommonPrefix3(String[] strs) {
        String tmp = strs[0];
        for (int i = 0; i < tmp.length(); i++) {
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].length() == i || tmp.charAt(i) != strs[j].charAt(i)) {
                    return tmp.substring(0, i);
                }
            }
        }
        return tmp;
    }
}
